/**
 * This file is Copyright © 2008 Software Craftsmen Limited. All Rights Reserved.
 */
package com.softwarecraftsmen.orogeny.buildLogs;

import com.softwarecraftsmen.orogeny.execution.SuccessOrFailure;
import org.jetbrains.annotations.NotNull;

import java.io.PrintStream;
import static java.lang.System.out;
import java.util.Set;

public class SimpleIndentingBuildLog implements IndentingBuildLog
{
	@NotNull
	public static SimpleIndentingBuildLog consoleIndentingBuildLog(final @NotNull Set<Verbosity> verbositiesToOutput)
	{
		return new SimpleIndentingBuildLog(out, verbositiesToOutput);
	}

	private final PrintStream printStream;
	private final Set<Verbosity> verbositiesToOutput;

	public SimpleIndentingBuildLog(final @NotNull PrintStream printStream, final @NotNull Set<Verbosity> verbositiesToOutput)
	{
		this.printStream = printStream;
		this.verbositiesToOutput = verbositiesToOutput;
	}

	public void writeMessage(final @NotNull Indentation indentation, final @NotNull String message)
	{
		writeLines(indentation, message);
	}

	public void writeMessage(final @NotNull Indentation indentation, final @NotNull SuccessOrFailure successOrFailure)
	{
		successOrFailure.writeToLog(this, indentation);
	}

	public void writeMessage(final @NotNull Verbosity verbosity, final @NotNull String message)
	{
		if (!verbositiesToOutput.contains(verbosity))
		{
			return;
		}
		writeLines(verbosity.indentation(), message);
	}

	private void writeLines(final @NotNull Indentation indentation, final String text)
	{
		for (String line : text.replace("\r\n", "\n").split("\n"))
		{
			writeLine(indentation, line);
		}
	}

	private void writeLine(final @NotNull Indentation indentation, final String line)
	{
		indentation.identation(printStream, "\t");
		printStream.println(line);
		printStream.flush();
	}
}
